package com.zzptc.my.bookreader;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zzptc.my.bookreader.Bean.Book;
import com.zzptc.my.bookreader.Bean.User;

import org.litepal.LitePal;

public class LoginActivity extends AppCompatActivity {
    EditText usnedit,psdedit;
    Button loginbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getBook();
        getUser();
        initview();
        setListener();
    }

    private void getBook() {
        new Book(0,"永恒国度","孤独漂流",R.mipmap.yhgd).save();
        new Book(0,"僵尸旅行","愚鸠",R.mipmap.jslx).save();
        new Book(0,"洪荒星辰道","爱做梦的懒虫",R.mipmap.hhxcd).save();
        new Book(0,"千秋不死人","第九天命",R.mipmap.qxbsr).save();
        new Book(0,"遮天之人王","风流江少",R.mipmap.ztzrw).save();
    }

    private void getUser() {
        User user=new User(0,"张三","123");
        User user2=new User(0,"李四","456");
        User user3=new User(0,"王五","789");
        user.save();
        user2.save();
        user3.save();
    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //接住参数
               String usn=usnedit.getText().toString().trim();
               String psd=psdedit.getText().toString().trim();
                User u=confirmUser(usn,psd);
                if (u==null){
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                }else {
                    Intent it=new Intent(LoginActivity.this,MainActivity.class);

                    //信息存储apply数据库
                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("userid",u.getId());
                    editor.putString("username",u.getUsername());
                    editor.apply();

                    startActivity(it);
                }
            }
        });
    }

    private User confirmUser(String usn, String psd) {
        for (User u: LitePal.findAll(User.class)){
            if (u.getUsername().equals(usn)&&u.getPassword().equals(psd)){
                return u;
            }
        }
        return null;
    }

    private void initview() {
        usnedit=findViewById(R.id.usnedit);
        psdedit=findViewById(R.id.psdedit);
        loginbtn=findViewById(R.id.loginbtn);
    }
}
